'''
给你一个按照非递减顺序排列的整数数组 nums，和一个目标值 target。请你找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target，返回 [-1, -1]。
你必须设计并实现时间复杂度为 O(log n) 的算法解决此问题。
示例 1：
输入：nums = [5,7,7,8,8,10], target = 8
输出：[3,4]
示例 2：
输入：nums = [5,7,7,8,8,10], target = 6
输出：[-1,-1]
示例 3：
输入：nums = [], target = 0
输出：[-1,-1]
提示：
0 <= nums.length <= 105
-109 <= nums[i] <= 109
nums 是一个非递减数组
-109 <= target <= 109
'''
class Solution:
    def searchRange(self, nums, target):
        left_index = self.searchIndex(nums, target, True)
        if left_index == len(nums) or nums[left_index] != target:
            return [-1, -1]
        right_index = self.searchIndex(nums, target, False) - 1 #注意返回left所以最右下标需-1
        return [left_index, right_index]
    def searchIndex(self, nums, target, find_index):
        n = len(nums)
        left, right = 0, n - 1
        while left <= right:
            mid = left + (right - left) // 2
            #finde_index为标志位，True查找最左下标，反之最右
            if nums[mid] > target or (find_index and nums[mid] == target):
                right = mid - 1
            else:
                left = mid + 1
        return left
#示例
if __name__ == '__main__':
    arr = [5, 7, 7, 8, 8, 8, 10]
    arr1 = [5, 5, 5, 5, 5, 5, 5]
    arr2 = []
    target = 8
    target1 = 5
    target2 = 6
    print(Solution().searchRange(arr, target))
    print(Solution().searchRange(arr, target1))
    print(Solution().searchRange(arr, target2))
    print(Solution().searchRange(arr1, target))
    print(Solution().searchRange(arr1, target1))
    print(Solution().searchRange(arr1, target2))
    print(Solution().searchRange(arr2, target))
    print(Solution().searchRange(arr2, target1))
    print(Solution().searchRange(arr2, target2))